<template>
  <div class="param-dialog" :style="showAnimation">
    <div class="back" @click="hide"></div>
    <div class="front">
      <div class="modal-header">
        <div class="mdoal-title">工艺参数信息</div>
        <Button type="primary" icon="md-add" @click="handleAdd"
          >添加参数信息</Button
        >
      </div>
      <Table :columns="columns" :data="tableData" :height="300" border>
        <template slot-scope="{ row }" slot="paramName">
          <Input
            v-model="row.paramName"
            disabled
            placeholder="请输入参数名称"
          />
        </template>
        <!-- <template slot-scope="{ row }" slot="paramValue">
          <Input v-model="row.paramValue" placeholder="请输入参数值" />
        </template> -->
        <template #paramValue="{ row, index }">
          <!-- <Input
            v-model="row.paramValue"
            @on-change="handleValueChange(row, index)"
            placeholder="请输入参数值"
          /> -->
          <InputNumber
            class="para-input"
            v-if="row.paramType === 0"
            v-model="row.paramValue"
            @on-blur="handleValueChange(row, index)"
          />
          <!-- :min="row.minValue ? parseFloat(row.minValue) : undefined"
            :max="row.maxValue ? parseFloat(row.maxValue) : undefined" -->
          <!-- @on-change="handleValueChange(row, index)" -->
          <i-switch
            v-else-if="row.paramType === 1"
            v-model="row.paramValue"
            size="large"
            @on-change="handleValueChange(row, index)"
          >
            <span slot="open">开</span>
            <span slot="close">关</span>
          </i-switch>
        </template>
        <template slot-scope="{ index }" slot="action">
          <Button type="error" size="small" @click="handleDelete(index)"
            >删除</Button
          >
        </template>
      </Table>
      <div class="modal-footer">
        <div class="modal-button" data-text="确定" @click="handleSubmit"></div>
        <div class="modal-button" data-text="取消" @click="handleCancel"></div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {
  Node,
  ParamData,
  ProcessNodeData,
  T_srv,
  Tsrv,
  ifs,
  vue,
  ts
} from './config';

interface config {
  // modalTitle?: string;
  // modalSize?: Array<number>;
  // config?: any;
  node: Node;
}

@T_srv.comp
export default class cParamDialog extends vue {
  @T_srv.prop() config: config;

  @T_srv.prop() id: string;

  private showAnimation: any = {};

  private currentNode: Node | null = null;

  private tankId: string = '';

  private parentId: string = '';

  private tableData: ParamData[] = [];

  private originData: ParamData[] = [];

  private submitStatus: boolean = true;

  private columns = [
    {
      title: '参数名称',
      slot: 'paramName',
      key: 'paramName'
    },
    {
      title: '参数值',
      slot: 'paramValue',
      key: 'paramValue'
    },
    {
      title: '操作',
      slot: 'action',
      width: 100,
      align: 'center'
    }
  ];

  created() {
    this.init();
  }

  private init(): void {
    this.initData();
    this.show();
  }

  private initData(): void {
    const node = this.config.node;
    this.currentNode = node;
    const data = node.getData() as ProcessNodeData;
    this.tankId = data.tankData[0].tankId;
    this.parentId = data.id;

    // 确保数据存在并且是数组
    const paramData = Array.isArray(data.paramData) ? data.paramData : [];

    // 深拷贝数据
    this.tableData = JSON.parse(JSON.stringify(paramData));

    // 添加参数配置
    this.setParaConfig(data);
  }

  // 添加参数配置
  private setParaConfig(data: ProcessNodeData) {
    // {"$and":[{"master_bill_id":{"$in":[""]}},{"para_id":{"$in":[""]}}]}
    const paraIds = data.paramData.map(row => row.paramId);
    const tankID = data.tankData[0].tankId;
    if (Tsrv.noValue(tankID) || Tsrv.noValue(paraIds)) {
      this.tableData = JSON.parse(JSON.stringify(data.paramData));
      this.originData = JSON.parse(JSON.stringify(data.paramData));
      return;
    }
    const filter = {
      $and: [
        { master_bill_id: { $in: [tankID] } },
        { para_id: { $in: paraIds } }
      ]
    };

    this.getTableData('tank_para_info', filter).then(rows => {
      if (rows && rows.length > 0) {
        // 找到rows与paramsRows中para_id相同的行，将rows中的para_type、set_up_limit,set_lower_limit添加到对应的paramsRows中
        // 确保数据存在并且是数组
        const paramData = Array.isArray(data.paramData) ? data.paramData : [];
        this.tableData = paramData.map((row, index) => {
          const item = rows.find(it => it.para_id === row.paramId);
          if (item) {
            const value =
              row.paramType === 0
                ? Tsrv.noValue(row.paramValue)
                  ? null
                  : parseFloat(row.paramValue as string)
                : row.paramType === 1
                ? Boolean(row.paramValue)
                : !isNaN(Number(row.paramValue)) // 新增数字转换检查
                ? Number(row.paramValue)
                : null; // 转换失败返回null或0等默认值

            return {
              ...row,
              paramValue: value,
              paramType: item.para_type,
              maxValue: item.set_up_limit,
              minValue: item.set_lower_limit
            };
          }
          return row;
        });
      }
      this.originData = JSON.parse(JSON.stringify(this.tableData));
    });
  }

  // 获取数据
  public getTableData(tableName: string, filter?: any): Promise<any> {
    return new Promise(resolve => {
      const gpd = new ts.T_getPartDataArg();
      gpd.setFunName(tableName).setLang(this.$i18n.locale || 'en-US');
      gpd.setDbType(Tsrv.globalVar.dbType.MYSQL);
      gpd.setPage(1, 99999);
      gpd.setFilter(filter || {});
      Tsrv.getData<any, ifs.I_getPartDataArg>(gpd)
        .then(([b, res, rows, msg]) => {
          if (!b) {
            msg && this.$msg(msg);
            resolve(false);
          }
          resolve(rows);
        })
        .catch(e => {
          // 正在加载
          console.error(e);
        });
    });
  }

  private handleAdd(): void {
    const filter = {
      // initSearch?: ifs.I_fv[] | ifs.I_filter;
      initSearch: [
        { field: Tsrv.globalVar.fieldName.masterBillId, value: this.tankId }
      ] as ifs.I_fv[]
    };
    Tsrv.utils
      .createModal('oMagicBox', {
        source: {
          field: 'tank_para_info',
          filter,
          limit: 9999
        },
        config: {
          isFunLayout: false
        }
      })
      .then(data => {
        if (data && data.length > 0) {
          for (let i = 0; i < data.length; i++) {
            const el = data[i];
            // 如果没有则新增，有则更新参数类型，参数范围
            const index = this.tableData.findIndex(
              it => it.paramId === el['para_id']
            );
            if (
              // this.tableData.findIndex(it => it.paramName === el['para_id']) ===
              // -1
              index === -1
            ) {
              // parseFloat(el['process_default_value'])
              const value =
                el['para_type'] === 0
                  ? Tsrv.noValue(el['process_default_value'])
                    ? null
                    : parseFloat(el['process_default_value'])
                  : el['para_type'] === 1
                  ? Boolean(el['process_default_value'])
                  : el['process_default_value'];
              this.tableData.push({
                id: Tsrv.getSnowIDFmtStr(),
                paramId: el['para_id'],
                paramName: el['m2o|para_id|para_info|title'],
                paramValue: value,
                paramType: el['para_type'],
                maxValue: el['set_up_limit'],
                minValue: el['set_lower_limit']
              });
            }
          }
        }
      });
  }

  private handleDelete(index: number): void {
    this.tableData.splice(index, 1);
  }

  private handleSubmit(): void {
    if (!this.currentNode) return;
    this.save().then((resp: any) => {
      if (resp) {
        // 过滤有效数据
        const validData = this.tableData.filter(
          item => item.paramName?.trim() || item.paramValue.toString()
        );

        // 更新节点数据
        const data = this.currentNode.getData() as ProcessNodeData;
        // 深拷贝过滤后的数据
        data.paramData = JSON.parse(JSON.stringify(validData));
        // 确保更新到节点
        this.currentNode.setData({ ...data });

        // 更新图标状态
        this.currentNode.setAttrs({
          paramIcon: {
            html: `<i class="ivu-icon ivu-icon-md-settings" style="font-size: 16px; color: ${
              validData.length ? '#1890ff' : '#999'
            }; cursor: pointer;" data-icon="param"></i>`
          }
        });
      }
      this.handleCancel();
    });
  }

  private save(): Promise<any> {
    const insertRecords = [];
    const removeRecords = [];
    const updateRecords = [];
    return new Promise((resolve, reject) => {
      if (!this.parentId) {
        resolve(false);
        return;
      }
      const ctd = new ts.T_ctdArg();
      ctd
        .setTableName('process_para_details')
        .setDbType(Tsrv.globalVar.dbType.MYSQL);
      ctd.setRule({} as ifs.I_rule);
      if (this.tableData.length > 0) {
        // 新增的记录
        this.tableData.forEach(item => {
          const index = this.originData.findIndex(it => it.id === item.id);
          if (index === -1) {
            const rows = [
              new ts.T_fv().setField('id').setValue(item.id),
              new ts.T_fv().setField('master_bill_id').setValue(this.parentId),
              new ts.T_fv().setField('para_id').setValue(item.paramId),
              new ts.T_fv()
                .setField('parameter_value')
                .setValue(item.paramValue)
            ] as ifs.I_fv[];
            insertRecords.push(rows);
          }
        });
        // 删除的记录
        this.originData.forEach(item => {
          const index = this.tableData.findIndex(it => it.id === item.id);
          if (index === -1) {
            removeRecords.push(item.id);
          }
        });
        // 修改的记录
        this.originData.forEach(item => {
          const index = this.tableData.findIndex(it => it.id === item.id);
          if (
            index > -1 &&
            item.paramValue !== this.tableData[index].paramValue
          ) {
            const rows = [
              new ts.T_fv().setField('id').setValue(item.id),
              new ts.T_fv()
                .setField('parameter_value')
                .setValue(this.tableData[index].paramValue)
            ] as ifs.I_fv[];
            updateRecords.push(rows);
          }
        });
      } else {
        if (this.originData.length > 0) {
          const removes = this.originData.map(item => item.id);
          removeRecords.push(...removes);
        }
      }
      if (
        !(
          insertRecords.length === 0 &&
          removeRecords.length === 0 &&
          updateRecords.length === 0
        )
      ) {
        if (insertRecords.length > 0) {
          const scope = {};
          // if (this.scope && this.scope?.field) {
          //   // scope = JSON.parse(`{"${this.scope.field}":${this.scope.value}}`);
          //   scope = { [`${this.scope.field}`]: this.scope.value };
          // }
          const bDatas: ifs.I_baseData[] = [];
          insertRecords.forEach(ele => {
            const bData = new ts.T_baseData();
            bData
              .setDataRule({} as ifs.I_rule)
              .setFileInfo({})
              .setRowData(...(ele as ifs.I_fv[]));
            bDatas.push(bData);
          });
          ctd.setInsRecDataMany(scope, ...bDatas);
        }
        if (removeRecords.length > 0) {
          const ids = `"${removeRecords.join(`","`)}"`;
          const filter = JSON.parse(`{"id":{"$in":[${ids}]}}`);
          ctd.setDelRecData({} as ifs.I_rule, filter);
        }
        if (updateRecords.length > 0) {
          let filter: any = {};
          const ctdUpdDatas: ifs.I_ctdUpdData[] = [];
          updateRecords.forEach(ele => {
            const ctdUpdData = new ts.T_ctdUpdData();
            ctdUpdData.setDataRule({} as ifs.I_rule).setFileInfo({});
            const rowData: ifs.I_fv[] = [];
            ele.forEach(item => {
              // 取出id作为过滤条件
              if (item?.field === 'id') {
                filter = { id: item?.value };
              } else {
                rowData.push(item);
              }
            });
            ctdUpdData.setFilter(filter);
            ctdUpdData.setRowData(...rowData);
            ctdUpdDatas.push(ctdUpdData);
          });
          ctd.setUpdRecDataMany(...ctdUpdDatas);
        }
        Tsrv.batRows(ctd).then(resp => {
          const [b, res, msg] = resp;
          msg && this.$msg(msg);
          if (b) {
            resolve(true);
          } else {
            resolve(false);
          }
        });
      }
    });
  }

  private handleCancel(): void {
    // this.visible = false;
    this.hide();
    this.currentNode = null;
    this.tableData = [];
  }

  private handleValueChange(row: ParamData, index: number) {
    if (typeof row.paramValue === 'number') {
      const value = row.paramValue;
      if (row.minValue && value < parseFloat(row.minValue)) {
        this.submitStatus = false;
        this.$Message.error(`值不能小于${row.minValue}`);
        // row.paramValue = row.minValue;
      } else if (row.maxValue && value > parseFloat(row.maxValue)) {
        this.submitStatus = false;
        this.$Message.error(`值不能大于${row.maxValue}`);
        // row.paramValue = row.maxValue;
      } else {
        this.submitStatus = true;
      }
    }
    this.tableData[index].paramValue = row.paramValue;
  }

  public show() {
    const that = this;
    this.showAnimation = {
      display: 'block',
      // 'z-index': 102 + this.id
      'z-index': 202 + this.id
    };
    setTimeout(() => {
      that.showAnimation = {
        display: 'block',
        opacity: 1,
        // 'z-index': 102 + this.id
        'z-index': 202 + this.id
      };
    }, 10);
  }

  public hide() {
    const that = this;
    this.showAnimation = {
      display: 'block',
      opacity: 0,
      // 'z-index': 102 + this.id
      'z-index': 202 + this.id
    };
    setTimeout(() => {
      that.showAnimation = {
        display: 'none',
        // 'z-index': 102 + this.id
        'z-index': 202 + this.id
      };
      this.$bus.$emit(`modal_${this.id}`, null);
    }, 200);
  }
}
</script>

<style lang="less" scoped>
.param-dialog {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  opacity: 0;
  display: none;
  transition: ease-in-out 0.2s;
  .back {
    background-color: rgba(0, 0, 0, 0.5);
    width: 100%;
    height: 100%;
  }
  .front {
    position: absolute;
    max-width: 560px;
    min-height: 150px;
    overflow: hidden;
    top: 30%;
    left: 50%;
    width: calc(100% - 30px);
    // height: calc(100% - 30px);
    transform: translate(-50%, -50%);
    border-radius: 10px;
    background-color: #fefcfa;
    box-shadow: 0px 50px 100px 15px #cead89;

    .para-input {
      width: 100%;
    }

    .modal-header {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      height: 50px;
      background-color: rgb(247, 247, 247);
      padding: 0 20px;
      .mdoal-title {
        font-size: 14px;
        font-weight: 700;
      }
    }

    .modal-footer {
      width: 100%;
      height: 45px;
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      align-items: center;
      .modal-button {
        width: calc(50% - 1px);
        transition: all 250ms ease-in-out;
        // background-color: #fdf3e9;
        background-color: #57a3f340;
        color: #818994;
        line-height: 45px;
        overflow: hidden;
        position: relative;
        text-align: center;
        text-decoration: none;
        text-transform: uppercase;

        &:before {
          content: attr(data-text);
          position: relative;
          z-index: 2;
        }

        &:after {
          transition: top 250ms ease-in-out;
          // background-color: darken(#fdf3e9, 5%);
          background-color: #2d8eff;
          content: '';
          height: 100%;
          left: 0%;
          position: absolute;
          top: 100%;
          width: 100%;
          z-index: 1;
        }

        &:hover {
          color: #fefcfa;
          &:after {
            top: 0;
          }
        }
      }

      &:first-child {
        border-right: 1px solid #fefcfa;
      }

      &:last-child {
        border-left: 1px solid #fefcfa;
      }
    }
  }
}
</style>
